package controller;

import common.tree.Node;
import common.tree.Tree;
import context.LoginUserCache;
import context.NativeCache;
import context.ResponseContext;
import context.UserContext;
import controller.entity.Result;
import entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.FunctionService;
import service.RoleService;
import service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by asus on 2017/6/18.
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private NativeCache nativeCache;
    @Autowired
    private RoleService roleService;
    @Autowired
    private FunctionService functionService;

    @RequestMapping("/index")
    public String index() {
        if (null != UserContext.getCurrent() && null != UserContext.getCurrent().getUser()) {
            System.out.println("UserContext.getCurrent" + UserContext.getCurrent().getUser());
            return "backmanage";
        }
        System.out.println("UserContext.getCurrent ==  null");
        return "/login.jsp";
    }

    @RequestMapping("/login_t")
    @ResponseBody
    public Result login(String username, String pwd, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(username + ":" + pwd);
        //非空校验
        User user = userService.getUser(username, pwd);
        System.out.println(user);
        if (null == user) {
            return Result.fail("用户名或密码错误");
        } else {
            try {
                request.getSession().setAttribute("username", user.getName());
                /*
                1、保存当前响应上下文
                2、将用户放进Cache
                3、设置cookie
                4、将用户对应的accordion放入cache
                 */
                ResponseContext.setCurrent(response);
                LoginUserCache.put(user);
                LoginUserCache.setCookie(user);
                List<UserRole> userRoles = userService.getUserRolesByUserId(user.getId());
                if (null == userRoles || userRoles.size() == 0) {
                    return Result.fail("该用户没有授权");
                }
                List<Long> roleIds = new ArrayList<>();
                for (UserRole userRole : userRoles) {
                    roleIds.add(userRole.getRoleId());
                }
                List<Role> roles = roleService.getRoles(roleIds);
                nativeCache.setRoles(user.getId(), roles);
                List<Node> nodes = getAccordion(false, user.getId());
                LoginUserCache.setAccorions(user.getName(), nodes);
                return Result.success();
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("未知错误");
            }

        }
    }

    @RequestMapping("/logout")
    public String logout() {
        if (null != UserContext.getCurrent() && null != UserContext.getCurrent().getUser()) {
            LoginUserCache.remove(UserContext.getCurrent().getUser().getName());
        }
        return "redirect:/login.jsp";
    }

    @RequestMapping("/details")
    public String details() {
        if (null != UserContext.getCurrent()) {
            System.out.println("UserContext.getCurrent" + UserContext.getCurrent().getUser());
        } else {
            System.out.println("UserContext== null");
        }
        return "backmanage";
    }

    private List<Node> getAccordion(boolean isAdmin, Long userId) {
        List<RoleFunction> roleFunctions = null;
        Set<Function> permissionFunction = new HashSet<>();
        for (Role role : nativeCache.getRoles(userId)) {
            System.out.println("role:" + role);
            roleFunctions = roleService.getRoleFunction(role.getId());
            System.out.println("roleFunctions:" + roleFunctions);
            for (RoleFunction rf : roleFunctions) {
                Function func = nativeCache.getFunction(rf.getFunctionId());
                System.out.println(func);
                permissionFunction.add(func);
            }
        }
        Tree tree = new Tree(new ArrayList<>(permissionFunction));
        return tree.build();
    }

    /**
     * 点击 “商品管理”后，
     * 进入 goods.jsp页面
     * @return
     */
    @RequestMapping("/goods")
    public String redirectGoods(){
        System.out.println("jinru goods");
        return "goods";
    }

    /**
     * 仓库经理身份登陆后，
     * 点击“登记员管理”
     * 页面跳转至“registrar.jsp”
     * @return
     */
    @RequestMapping("/registrar")
    public String  redirectRegistrar(){
        return "registrar";
    }

    /**
     * 登记员身份进入后
     * 点击“商品入库管理”
     * 页面跳转至“goodsinstore.jsp”
     * @return
     */
    @RequestMapping("/goodsinstore")
    public String redirectGoodsinstore(){return "goodsinstore";}

    @RequestMapping("/usermanage")
    public String redirectUserManage(){return "usermanage";}

    /*
    //非递归，仅支持二级菜单
    private void completeAccordion(List<AccordionDTO> permissionAccordionDTOSet, AccordionDTO rootAccordionDTO) {
        for (AccordionDTO accordionDTO : permissionAccordionDTOSet) {
            if (accordionDTO.getParentId() == rootAccordionDTO.getId()) {
                rootAccordionDTO.getChildren().add(accordionDTO);
                System.out.println("completeAccordion:"+rootAccordionDTO.getChildren());
            }
        }
    }
    */
}
